<?php

namespace App\Services\My;

use App\Constants\IncomeType;
use App\Constants\VipType;
use App\Dao\CommonSettingDao;
use App\Dao\GiftDao;
use App\Dao\UserRemarkDao;
use App\Model\CashDraw;
use App\Model\Gift;
use App\Model\Guild;
use App\Model\IncomeExpense;
use App\Model\Order;
use App\Model\PayCall;
use App\Model\UserRemark;
use App\Model\WithdrawAccount;
use App\Utils\MemcacheClient;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use function Hyperf\Stringable\str;
use function Hyperf\Translation\trans;

class WalletService
{

    /**
     * Note - 提现记录列表
     * DateTime 2024/8/12 15:11
     * User Admin
     * @param $uid
     * @param array $params
     * @return array
     */
    public function cashRecord($uid, array $params)
    {
        $page = intval($params['page']);
        $pagesize = 20;
        $start = ($page - 1) * $pagesize;
        $type = $params['type'] ?? 0; //0全部 1已提现 2提现中 3提现失败

        // $where = "uid=?";
        // $bindVal = [$uid];
        $where[] = ['uid', '=', $uid];

        if ($type == 1) {
            // $where = "uid=? and status=?";
            // $bindVal = [$uid, 2];
            $where[] = ['status', '=', 2];
        }

        if ($type == 2) {
            // 0待审核，1平台审核通过  2已打款 3已拒绝 4正在打款（批量）5打款失败（批量）6自动付款失败 7财务审核通过
            // $where = "uid=? and status in (0,1,4,6,7)";
            // $bindVal = [$uid];
            // $where[] = ['status', 'in', [0, 1, 4, 6, 7]];
            $where[] = [function ($query) {
                return $query->whereIn('status', [0, 1, 4, 6, 7]);
            }];
        }

        if ($type == 3) {
            // $where = "uid=? and status in (3,5)";
            // $bindVal = [$uid];
            // $where[] = ['status', 'in', [3, 5]];
            $where[] = [function ($query) {
                return $query->whereIn('status', [3, 5]);
            }];
        }

        $drawcashModel = new CashDraw();
        // $cache = $drawcashModel->findAll('id,ctime,actual_amount,amount,status,cash_type,tax, alipay_result as result_desc ', $where, $bindVal, 'ctime desc', "limit $start,$pagesize");
        $cache = $drawcashModel->newQuery()->where($where)->orderBy('ctime', 'desc')->offset($start)->limit($pagesize)->get()->toArray();
        if (!empty($cache)) {
            foreach ($cache as $k => $v) {
                $ctime = $v['ctime'];
                $cache[$k]['ctime'] = date('H:i:s', $ctime);
                $cache[$k]['cdate'] = date('Y/m/d', $ctime);
                $cache[$k]['cash_type'] = strval($v['cash_type'] == 1 ? 0 : 1);
                $cache[$k]['apply_amount'] = strval($v['amount'] / GOLD_RATIO);
            }
        }
        return formatData(['result' => 1, 'msg' => $cache]);
        // Tool::JSON(\CodeData::SUCCESS, array('result' => 1, 'msg' => $cache), '');
    }


    /**
     * Note - 充值明细列表
     * DateTime 2024/8/12 15:44
     * User Admin
     * @param mixed $uid
     * @param array $params
     */
    public function payRecord(mixed $uid, array $params)
    {
        $page = intval($params['page']);
        $page <= 0 && $page = 1;
        $pagesize = 20;
        $language = $params['language'];
        $cache = MemcacheClient::getInstance()->get('pay_record_' . $uid . '_' . $page . '_' . $pagesize);
        if (!$cache) {
            $incomeExpenseModel = new IncomeExpense();
            $list = $incomeExpenseModel->getRechargeList($uid, $page, $pagesize);
            $cache = [];
            foreach ($list as $val) {
                $ctime = $val['ctime'];

                $val['ctime'] = date('H:i:s', $ctime);
                $val['cdate'] = date('Y/m/d', $ctime);

                if ($val['sub_type'] == 1) {
                    $val['goods_des'] = trans('message.充值', [], $language) . ' ' . intval($val['amount']) . ' ' . trans('message.金币', [], $language);
                } elseif ($val["sub_type"] == 5) {
                    if (isset($val['extend']) && $extent = json_decode($val['extend'])) {
                        $orderInfo = Order::query()->where('order_id', $extent->orderid)->first();
                        if ($orderInfo['consume_type'] > 50 && $orderInfo['consume_type'] <= 70) {
                            $val['goods_des'] = VipType::getVipTypeInfo($orderInfo['consume_type']) . trans('message.赠送', [], $language);
                        } else {
                            $val['goods_des'] = trans('message.充值赠送', [], $language);
                        }
                    } else {
                        $val['goods_des'] = trans('message.充值赠送', [], $language);
                    }
                }
                $val['goods'] = intval($val['amount']);
                $cache[] = $val;
            }
            MemcacheClient::getInstance()->set('pay_record_' . $uid . '_' . $page . '_' . $pagesize, $cache, 300);
        }
        return formatData(['result' => 1, 'msg' => $cache]);
        // Tool::JSON(\CodeData::SUCCESS, array('result' => 1, 'msg' => $cache), '');
    }


    /**
     * Note - 收支明细
     * DateTime 2024/8/12 16:17
     * User Admin
     * @param $uid
     * @param array $params
     * @return array
     */
    public function incomeExpense($uid, array $params)
    {
        $type = $params['type'];//1-收益、2-支出
        $page = intval($params['page']);
        $page <= 0 && $page = 1;
        $pagesize = 20;
        $sub_type = $params['sub_type'] ?? 0;
        $language = $params['language'];

        $cache = MemcacheClient::getInstance()->get('user_income_expense_' . $uid . '_' . $type . '_' . $page . '_' . $pagesize);
        if ($cache === false) {
            $incomeExpenseModel = new IncomeExpense();
            $cache = $incomeExpenseModel->getList($uid, $type, $page, $pagesize, intval($sub_type));
            if (!empty($cache)) {
                $incomeExpenseType = trans('payment_type', [], $language);

                foreach ($cache as &$v) {
                    $gold_from = json_decode($v['gold_from'], true);
                    $v['send_gold'] = ($gold_from['chat_count'] ?? 0) + ($gold_from['sys_send_count'] ?? 0) + ($gold_from['recharge_send_count'] ?? 0);

                    $v['send_gold'] = strval($v['send_gold']);

                    $ctime = $v['ctime'];
                    $v['ctime'] = date('H:i:s', $ctime);
                    $v['cdate'] = date('Y/m/d', $ctime);

                    $add = '';
                    if ($uid == $v['inviteUid']) {
                        $add = '(' . trans('message.邀请用户', [], $language) . ')';
                    }
                    $v['sub_type'] = ($incomeExpenseType[$v['sub_type']]['name'] ?? $v['sub_type']) . $add;
                }
            }
            MemcacheClient::getInstance()->set('user_income_expense_' . $uid . '_' . $type . '_' . $page . '_' . $pagesize, $cache, 300);
        }
        // Tool::JSON(\CodeData::SUCCESS, array('result' => 1, 'msg' => $cache), '');
        return formatData(['result' => 1, 'msg' => $cache]);
    }


    /**
     * Note -
     * DateTime 2024/8/12 16:58
     * User Admin
     * @param mixed $userInfo
     * @param $params
     * @return array
     */
    public function callIncome(mixed $userInfo, $params)
    {
        $uid = $userInfo['id'];
        $page = $params['page'] ?? 1;
        $pagesize = $params['pagesize'] ?? 20;
        $pagesize == 0 && $pagesize = 20;
        // 1: 视频聊天  2:语音聊天
        $call_type = $params['call_type'] ?? 1;
        $language = $params['language'];

        $query = PayCall::query()->from('tb_pay_call AS p');

        if ($userInfo['sex'] == 1) {  //男
            // $where = " user_id = ? ";
            // $join = "inner join tb_user u on p.anchor_id = u.id";
            // $bindVal[] = $uid;
            $query->where('user_id', $uid)->join('tb_user AS u', 'p.anchor_id', '=', 'u.id');
        } else {
            // $where = " anchor_id = ? ";
            // $join = "inner join tb_user u on p.user_id = u.id";
            // $bindVal[] = $uid;
            $query->where('anchor_id', $uid)->join('tb_user AS u', 'p.user_id', '=', 'u.id');
        }

        // $where .= " and p.is_robot=0 and end_time>0";
        $query->where('p.is_call_mass', 0)->where('end_time', '>', 0);

        if ($call_type) {
            // $where .= " and p.type=?";
            // $bindVal[]=$call_type;
            $query->where('p.type', $call_type);
        }

        $list = $query->selectRaw('p.id,p.card_id,p.ext,type,end_time,start_time,anchor_id,user_id,p.is_call_mass,fare,profit,p.free_video_time,u.nickname,u.inviteUid')
            ->orderBy('p.id', 'desc')
            ->offset(($page - 1) * $pagesize)
            ->limit($pagesize)->get()->toArray();

        $records = array();
        $remarks = [];
        if ($userInfo['sex'] == 2) {
            $remarks = UserRemarkDao::getInstance()->getOne($userInfo['id']);
        }
        $giftModel = new Gift();
        if (!empty($list)) {
            $inviteTrans = trans('message.邀请用户', [], $language);
            $videoCallTrans = trans('message.视频通话', [], $language);
            $videoQuickCallTrans = trans('message.视频速聊', [], $language);
            $voiceCallTrans = trans('message.语音通话', [], $language);
            $voiceQuickCallTrans = trans('message.语音速配', [], $language);
            foreach ($list as $v) {
                $record = array();
                $record["id"] = intval($v["id"]);
                $record["type"] = intval($v["type"]);
                $record["duration"] = $v["end_time"] - $v["start_time"] - $v['free_video_time'];
                if ($userInfo['sex'] == 1) {
                    //男
                    $record["duration"] = $v["end_time"] - $v["start_time"] - $v['free_video_time'];
                }
                $remarks_name = '';
                if ($userInfo['sex'] == 2) {
                    $remarks_name = (!empty($remarks[$v['user_id']])) ? $remarks[$v['user_id']]['remarks_name'] : '';
                }
                if ($uid == $v["inviteUid"]) {
                    $add = '(' . trim($remarks_name . ',' . $inviteTrans, ',') . ')';
                } else {
                    $add = $remarks_name;
                }
                $record["user_id"] = $v['user_id'];
                $record["free_video_time"] = $v['free_video_time'];
                $record["user_name"] = $v['nickname'] . $add;
                $record["start_time"] = intval($v["start_time"]);
                $record["fare"] = intval($v["fare"]);
                $record["profit"] = $v["profit"];
                $record["card_id"] = $v["card_id"];

                $record["send_gold"] = json_decode($v['ext'], true)['send_gold'] ?? 0;

                $record['is_call_mass'] = $v['is_call_mass'];

                if ($v['type'] == 1) {
                    $record['call_from'] = $v['is_call_mass'] == 0 ? $videoCallTrans : $videoQuickCallTrans;
                } else {
                    $record['call_from'] = $v['is_call_mass'] == 0 ? $voiceCallTrans : $voiceQuickCallTrans;
                }

                if ($userInfo['sex'] == 1) {
                    //算出用户送礼支出
                    $record['gift_amount'] = $giftModel->getGiftCost($uid, $v['id']);
                } else {
                    //算出主播收礼收入
                    $record['gift_amount'] = $giftModel->getGiftProfit($uid, $v['id']);
                }

                $records[] = $record;
            }
        }
        return formatData(['result' => 1, 'msg' => $records]);
        // Tool::JSON(\CodeData::SUCCESS, array(
        //     'records' => $records,
        // ));
    }


    /**
     * Note - 个人中心-钱包
     * DateTime 2024/8/15 12:12
     * User Admin
     * @param $userInfo
     */
    public function wallet($userInfo)
    {
        $uid = $userInfo['id'];
        $userInfo["gold_ratio"] = GOLD_RATIO;
        $info = [
            'id' => $userInfo['id'],
            'nickname' => $userInfo['nickname'],
            'sex' => $userInfo['sex'],
            'gift_count' => $userInfo['gift_count'] + $userInfo['chat_count'] + $userInfo['sys_send_count'] + $userInfo['recharge_send_count'],
            'chat_count' => $userInfo['chat_count'],
            'integrate_usable_count' => $userInfo['integrate_usable_count'],
            'integrate_freeze_count' => $userInfo['integrate_freeze_count'],
            'is_cardAuth' => $userInfo['is_cardAuth'],
            'is_faceAuth' => $userInfo['is_faceAuth'],
            'gold_ratio' => GOLD_RATIO,
        ];
        // $withdrawAccountModel = new WithdrawAccountModel();
        $account = WithdrawAccount::getAccount($uid);
        $draw_type = [
            'alipay_id' => $account['alipay_id'] ?? '',
            'alipay_id_status' => $account['alipay_id_status'] ?? 0,
            'bank_num' => $account['bank_num'] ?? '',
            'bank_num_check_status' => $account['bank_num_check_status'] ?? 0,
        ];

        // 获取超推数据
        // $guild = $withdrawAccountModel->find("id,guild_num,uid,cash_method","uid = ?",[$uid],"","tb_guild");
        $guild = Guild::query()->select(['id', 'guild_num', 'uid', 'cash_method'])->where("uid", $uid)->first();

        $guild_balance = 0;
        $info['integrate_usable_count'] = bcadd(strval($info['integrate_usable_count']), str($guild_balance), 2);

        if ($info['integrate_usable_count'] < 0) {
            $info['integrate_freeze_count'] = floatval($info['integrate_freeze_count']) + floatval($info['integrate_usable_count']);
            $info['integrate_usable_count'] = 0;
        }
        $cash_method = $guild['cash_method'] ?? CommonSettingDao::getValue('cash_method');    // 0支付宝+银行卡 1银行卡 2支付宝

        $times = strtotime(date("Ymd"));
        // 今日收益
        // $info['today_income'] = $withdrawAccountModel->findOneField("select sum(amount) sum_amount from tb_income_expense where ctime > $times and sub_type <> 35 and type = 1 and amount_type=2 and uid = $uid", "sum_amount") ?: '0.0';
        $info['today_income'] = IncomeExpense::query()->where('ctime', '>', $times)->where('sub_type', '<>', IncomeType::PROMOTION_DIVIDEND)->where('type', 1)->where('amount_type', 2)->where('uid', $uid)->sum('amount');
        // 邀请收益
        // $info['today_invite_income'] = $withdrawAccountModel->findOneField("select sum(amount) sum_amount from tb_income_expense where ctime > $times and sub_type = 35 and type = 1 and amount_type=2 and uid = $uid", "sum_amount") ?: '0.0';
        $info['today_invite_income'] = IncomeExpense::query()->where('ctime', '>', $times)->where('sub_type', IncomeType::PROMOTION_DIVIDEND)->where('type', 1)->where('amount_type', 2)->where('uid', $uid)->sum('amount');

        return formatData([
            'result' => 1,
            'msg' => [
                'user' => $info,
                'draw_type' => $draw_type,
                'cash_method' => $cash_method,    // 0支付宝+银行卡 1银行卡 2支付宝
                'ali' => [
                    ['money' => '50', 'integral' => '500', 'rate' => '7'],
                    ['money' => '100', 'integral' => '1000', 'rate' => '7'],
                    ['money' => '150', 'integral' => '1500', 'rate' => '7'],
                    ['money' => '200', 'integral' => '2000', 'rate' => '7'],
                    ['money' => '300', 'integral' => '3000', 'rate' => '7'],
                    ['money' => '500', 'integral' => '5000', 'rate' => '7'],
                    ['money' => '1000', 'integral' => '10000', 'rate' => '7'],
                    ['money' => '3000', 'integral' => '30000', 'rate' => '7']
                ],
                'bank' => [
                    ['money' => '50', 'integral' => '500', 'rate' => '6'],
                    ['money' => '100', 'integral' => '1000', 'rate' => '6'],
                    ['money' => '150', 'integral' => '1500', 'rate' => '6'],
                    ['money' => '200', 'integral' => '2000', 'rate' => '6'],
                    ['money' => '300', 'integral' => '3000', 'rate' => '6'],
                    ['money' => '500', 'integral' => '5000', 'rate' => '6'],
                    ['money' => '1000', 'integral' => '10000', 'rate' => '6'],
                    ['money' => '3000', 'integral' => '30000', 'rate' => '6']
                ]
            ]
        ]);

    }

}